package com.ts.notice.controller;

import com.ts.common.core.utils.Result;
import com.ts.notice.dto.SMSDto;
import com.ts.notice.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
@Slf4j
public class SMSController {

    @Autowired
    private RedisTemplate redisTemplate;

    private String loginSmsKey = "ts:notice:login:%s-%s"; // ts:notice:login:10086-0123

    @Autowired
    private SMSUtils smsUtils;

    @GetMapping("/send") // ?phone=1100
    public Result send(String phone) {

        if (ObjectUtils.isEmpty(phone)) {
            return new Result().error("手机号为空");
        }

        // 1、生成验证码
        String code = RandomStringUtils.random(4,false,true);

        // 2、把验证码保存到redis中
        String key = String.format(loginSmsKey, phone, code);
        redisTemplate.opsForValue().set(key, code, 60, TimeUnit.SECONDS);

        // 3、线程池中申请一个线程来发送短信，发送验证码到用户的手机号
        SMSDto smsDto = new SMSDto();
        smsDto.setMobile(phone);
        smsDto.setCode(code.toString());
//        smsUtils.send(smsDto);
        log.debug("smsDto:{}", smsDto);

        return new Result().viewOk(null);
    }
}
